package kr.bae.androidcomplete02.ch12;

import java.util.ArrayList;

import kr.bae.androidcomplete02.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ListAddDelete extends Activity {
	ArrayList<String> arItems;
	ArrayAdapter<String> adapter;
	ListView list;
	EditText et;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch12_listadddel);
		
		et = (EditText) findViewById(R.id.ch12_edit_newitem);

		arItems = new ArrayList<>();
		arItems.add("first");
		arItems.add("second");
		arItems.add("third");
		arItems.add("fourth");
		arItems.add("fifth");

		adapter = new ArrayAdapter<>(this,
				android.R.layout.simple_list_item_checked, arItems);

		list = (ListView) findViewById(R.id.ch12_listview_adddel);
		list.setAdapter(adapter);
		list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String msg;
				msg = "Select Item = " + adapter.getItem(position);
				Toast.makeText(getApplication(), msg, Toast.LENGTH_SHORT).show();
			}
		});
		
		list.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				//int pos = list.getSelectedItemPosition();
				if(position != ListView.INVALID_POSITION) {
					arItems.remove(position);
					list.clearChoices();
					adapter.notifyDataSetChanged();
				}
				
				return false;
			}
		});
	}

	public void mOnClick(View v) {
				
		switch (v.getId()) {
		case R.id.ch12_btn_add:
			String text = et.getText().toString();
			arItems.add(text);
			et.setText("");
			adapter.notifyDataSetChanged();
			break;

		case R.id.ch12_btn_del:
			int pos = list.getCheckedItemPosition();
			if(pos != ListView.INVALID_POSITION) {
				arItems.remove(pos);
				list.clearChoices();
				adapter.notifyDataSetChanged();
			}
			break;

		default:
			break;
		}
	}
}
